import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import {
  getTokenFromCookies,
  canTurnTo,
  setTitle,
  setTokenToCookies
} from '@/libs/util'
import config from '@/config'
const {
  homeName
} = config

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'history' // 是否开启 url 美化，发现 bug ：如果不开启 history， vue-router 的 next({name:'login'})操作不会走 afterEach
})
const LOGIN_PAGE_NAME = 'login'

/**
 * 权鉴方法调用入口
 * @param {*} name 即将跳转的路由name
 * @param {*} access 用户权限数组
 * @param {*} routes 路由列表
 */
const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) { // 有权限，可访问
    next()
  } else {
    next({
      replace: true,
      name: 'error_401'
    })
  } // 无权限，重定向到401页面
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getTokenFromCookies()
  if (!token && (to.name !== LOGIN_PAGE_NAME)) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: 'login'
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      turnTo(to, store.state.user.access, next)
    } else {
      store.dispatch('getUserInfoExcute').then(user => {
        // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
        turnTo(to, user.roles, next)
      }).catch((res) => {
        setTokenToCookies('')
        next({
          name: 'login'
        })
      })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
